package com.sylli.oeuf.server.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sylli.oeuf.server.exception.BasedException;
import com.sylli.oeuf.server.exception.ExceptionCause;

public class FileUtil {
	
	private static Logger log = LoggerFactory.getLogger( "util.file" );
	
	public static void copyfile(File srcFile, File destFile, boolean append) 
			throws BasedException {
	    try{
	      InputStream in = new FileInputStream(srcFile);
	      
	      //For Overwrite the file. (TRUE -> appends, FALSE -> overwrite)
	      OutputStream out = new FileOutputStream(destFile, append);

	      byte[] buf = new byte[1024];
	      int len;
	      while ((len = in.read(buf)) > 0){
	        out.write(buf, 0, len);
	      }
	      in.close();
	      out.close();
	      log.info("File copied.");
	    } catch(Exception ex) {
	      throw new BasedException(ExceptionCause.FileIOFail, 
	    		  "Copy: SourceFile = " + srcFile.getAbsolutePath() 
	    		  + ", DestinationFile = " + destFile.getAbsolutePath(), ex);
	    }
	}
	
	public static void writeToFile(String str, File fobj) throws BasedException {
		try {
			FileWriter fstream = new FileWriter(fobj);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(str);
			out.close();
		} catch (Exception e) {
			throw new BasedException(ExceptionCause.FileIOFail, 
					"Failed to write file = " + fobj.getAbsolutePath(), e);
		}
	}
	
	public static String readFromFile(File fobj) throws BasedException {
		try {
			FileReader fstream = new FileReader(fobj);
			BufferedReader in = new BufferedReader(fstream);
			String buffed = "";
			while (in.ready()) {
				buffed += in.readLine();
			}
			return buffed;
		} catch (Exception e) {
			throw new BasedException(ExceptionCause.FileIOFail,
					"Failed to read file = " + fobj.getAbsolutePath(), e);
		}
	}
}
